'use strict'

import Vue from 'vue'
import axios from 'axios'
import router from '../router.js'
import store from '../store.js'
import Util from '../Logic/Util.js'
import Api from '../api/UserApi.js'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: 'http://192.168.0.127:7000'
  baseURL: 'http://106.14.183.14:7000'
  //  baseURL: 'http://192.168.0.156:8080'

  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
}

const _axios = axios.create(config)

_axios.interceptors.request.use(
  function(config) {
    //如果vuex中存在token
    if (
      config.url === Api.login ||
      config.url === Api.forget ||
      config.url === Api.registe ||
      config.url == Api.checkCode ||
      config.url === Api.updatePassword
    ) {
      return config
    }
    if (store.state.token) {
      let vali = Util.checkValid(store.state.user.exp)
      if (vali) {
        config.headers.Authorization = `Bearer ${store.state.token}`
      } else {
        router.push({
          name: 'login'
        })
      }
    }
    // store.state.token;
    //store.commit('resetToken',token);
    //store.commit('clearToken',token);
    // config.headers.Authorization =  `Bearer ${store.state.token}`;
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    // window.console.log(response);
    if (response.data.status === 1 && response.data.msg === 'token无效') {
      store.commit('clearToken')
      router.push({
        name: 'login'
      })
    }
    return response
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error)
  }
)

Plugin.install = function(Vue) {
  Vue.axios = _axios
  window.axios = _axios
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios
      }
    },
    $axios: {
      get() {
        return _axios
      }
    }
  })
}

Vue.use(Plugin)

export default Plugin
